<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    function print(arr, mapper) {
        const newArr = []
        for (let i = 0; i < arr.length; i++) {
            const newItem = mapper(arr[i])
            newArr.push(newItem)
        }

        console.log("函数翻倍:", newArr)
    }

    print([1, 2, 3, 4, 5], (n) => n * 2)
    print([1, 2, 3, 4, 5], (n) => {
        return {oldVal: n, newVal: n * 2}
    })

    function sum(arr) {
        return arr.reduce((pre, cur) => pre + cur, 0)
    }

    console.log("reduce求和:", sum([1, 2, 3, 4, 5]))


    function calcCount(arr) {
        return arr.reduce((acc, cur) => {
            acc[cur] = (acc[cur] || 0) + 1
            return acc
        }, {})
    }

    console.log("统计元素出现的次数:", calcCount(([1, 2, 3, 2, 4, 2, 5])))


    function flatten(arr) {
        return arr.reduce((acc, cur) => [...acc, ...cur], [])
    }

    console.log("reduce扁平化(只适用于两层)：", flatten([[1, 2, 3], [4, 5, 6]]))

    function mySort(arr) {
        return arr.sort((x, y) => x.id - y.id)
    }

    console.log("sort排序,id升序:", mySort([{id: 2, name: 'jack2'}, {id: 3, name: 'jack3'}, {id: 2, name: 'jack2'}, {
        id: 1,
        name: 'jack1'
    }]))
</script>
</body>
</html>
